const User = require('../../models/User');
const jwt = require('jsonwebtoken');
const fs = require('fs');
const uploadUrl = require('../../libs/uploadUrl');
module.exports = app => {
    const express = require('express');
    const router = express.Router({
        mergeParams: true
    });
    const visitorRouter = express.Router({
        mergeParams: true
    });
    const assert = require('http-assert');
    const resourcesMiddleware = require('../../middleware/resource');
    const authMiddleware = require('../../middleware/auth')
    const powerMiddleWare = require('../../middleware/power')

    router.post('/', powerMiddleWare(), async (req, res) => {
        const model = await req.Model.create(req.body);
        res.send(model);
    })

    router.get('/', async (req, res) => {
        const model = req.Model;
        let page = req.query.pageNum || 1;
        let limit = req.query.pageSize || 10;
        const query = req.query.query;
        const reg = new RegExp(query, 'i') //不区分大小写
        let total = 0;
        const populateOption = {};
        let queryOptions = {};
        switch (model.modelName) {
            case 'User':
                populateOption.populate = 'role';
                break;
            case 'Demo':
                populateOption.populate = 'tags';
                break;
            case 'Comment':
                populateOption.populate = 'object';
                break;
            default:
                break;
        }
        const plusReg = ['Article', 'User', 'Demo', 'Tag', 'Comment'];
        const valid = plusReg.filter(item => { return item === model.modelName })

        if (valid.length) {
            queryOptions = { $or: [{ username: { $regex: reg } }, { title: { $regex: reg } }, { name: { $regex: reg } }, { content: { $regex: reg } },] }
        }
        model.find({}, async (err, data) => {
            if (err) return res.status(500).json({
                error_info: '请求失败！'
            })
            total = data.length;
        })

        const result = await model.find(queryOptions).sort({ weight: -1, createdAt: -1 }).setOptions(populateOption).skip((page - 1) * parseInt(limit)).limit(parseInt(limit));
        query && (total = result.length);
        res.send({
            data: result,
            total
        })
    })
    router.get('/:id', async (req, res) => {
        const options = {};
        if (req.Model.modelName === 'Article') {
            options.select = '+body';
        }
        const model = await req.Model.findById(req.params.id).setOptions(options);
        res.send(model);
    })

    router.put('/:id', powerMiddleWare(), async (req, res) => {
        const model = await req.Model.findByIdAndUpdate(req.params.id, req.body);
        res.send(model);
    })

    router.delete('/:id', powerMiddleWare(), async (req, res) => {
        await req.Model.findByIdAndDelete(req.params.id);
        res.send({
            success: true
        })
    })
    //通用CRUD接口
    app.use('/admin/api/rest/:resource', authMiddleware(), resourcesMiddleware(), router);
    //访客管理相关接口
    const Visitor = require('../../models/Visitor');
    app.use('/admin/api/visitor', visitorRouter);
    //访客列表
    visitorRouter.get('/list', authMiddleware(), async (req, res) => {
        let page = req.query.pageNum || 1;
        let limit = req.query.pageSize || 10;
        const query = req.query.query;
        const reg = new RegExp(query, 'i');
        const queryOptions = { $or: [{ visitorName: { $regex: reg } }, { visitorId: { $regex: reg } }] };
        const visitors = await Visitor.find(queryOptions).sort({ createdAt: -1 }).skip((page - 1) * parseInt(limit)).limit(parseInt(limit));
        const total = await Visitor.countDocuments();
        res.send({
            visitors,
            total
        })
    })
    //访客详情
    visitorRouter.get('/:id', authMiddleware(), async (req, res) => {
        const id = req.params.id;
        const Comment = require('../../models/Comment');
        const comments = await Comment.find({
            visitor_id: id
        }).populate('object')
        res.send({
            comments,
        })
    })

    //其他
    app.use('/admin/api/user', authMiddleware(), (req, res) => {
        res.send(req.user.username);
    })

    //文件上传中间件
    const multer = require('multer')
    const upload = multer({
        dest: __dirname + '/../../uploads'
    })
    app.post('/admin/api/upload', upload.single('file'), async (req, res) => {
        const file = req.file;
        file.url = `${uploadUrl}/uploads/${file.filename}`;
        res.send(file);
    })
    app.post('/admin/api/resumeupload', upload.single('file'), async (req, res) => {
        const file = req.file;
        const oldPath = __dirname + '/../../uploads/' + file.filename;
        const newPath = __dirname + '/../../uploads/' + file.originalname;
        file.path = newPath;
        fs.rename(oldPath, newPath, (err) => {
            if (err) throw err;
            res.send(file)
        })
    })
    //登录
    app.post('/admin/api/login', async (req, res) => {
        //1、找出用户
        const { username, password } = req.body;
        const user = await User.findOne({ username }).select('+password')
        assert(user, 422, '用户不存在');
        //2、校验密码
        const isValid = require('bcrypt').compareSync(password, user.password)
        assert(isValid, 422, '密码错误')
        //3、返回token
        const token = jwt.sign({ id: user._id }, app.get('secret'));
        res.send({ token, user });
    })


    //统一捕获并处理异常
    app.use(async (err, req, res, next) => {
        res.status(err.statusCode || 500).send({
            message: err.message
        })
    });
}